/**
 * @author wangze
 * @date 2017-12-14 11:26.
 **/
;(function () {
    'use strict';

    //var exporter ={};

    function getDefaultRequest(request) {
        request.page = request.current;
        request.pageSize = request.rowCount;
        request.sort = request.sort;
        //request.searchPhrase = request.searchPhrase || new Date().getTime();
        delete request.searchPhrase
        delete request.current;
        delete request.rowCount;
        delete request.sort;
        return request;
    }

    function getRequestHanlder(handler, opt) {
        return function (request) {
            request = getDefaultRequest(request);
            request = handler(request);
            if (opt.ajaxSettings.contentType.indexOf('application/json') != -1) {
                return JSON.stringify(request);
            } else {
                return request;
            }
        }
    }

    function getDefaultResponse(response) {
        // if (!(response && response.flag === true))
        //    throw  new Error('数据加载失败');
        var data = response.data || {};
        var result = {
            current: data.pageNumber? data.pageNumber: 0,
            rowCount: data.pageSize || 10,
            rows: data.items || [],
            total: data.totalItemsCount ? data.totalItemsCount : 0
        };
        if (result.rows && result.rows.length > 0) {
            $.each(result.rows, function (i) {
                result.rows[i].Index = (result.current - 1) * result.rowCount + i + 1;
            });
            return result;
        }
        return result;
    }

    function getResponseHandler(handler) {
        return function (response) {
            response = getDefaultResponse(response);
            return handler(response);
        }
    }


    var defaultGridOpt = {
        id: '#grid',//默认table id
        labels: {
            all: "全部",
            infos: "显示{{ctx.start}}至{{ctx.end}},共{{ctx.total}}条数据",
            loading: "加载中,请稍等...",
            noResults: "对不起,暂无数据！",
            refresh: "刷新",
            search: "查找"
        },
        post: function () {
            return $('#form-search').serializeObject();
        },
        ajaxSettings: {
            contentType: 'application/json; charset=utf-8'
        },
        rownumbers: true,
        selection: true,
        multiSelect: true,
        rowSelect: true,
        keepSelection: false,
        sorting: true,//默认不排序
        ajax: true,
        requestHandler: function (request) {
            return request;
        },
        responseHandler: function (response) {
            return response;
        },
        events: [],
        isPager: false,
        noTotal: false
    };
    var noLables = {
        all: "全部",
        infos: '',
        loading: "加载中,请稍等...",
        noResults: "对不起,暂无数据！",
        refresh: "刷新",
        search: "查找"
    };
    var noPagerOpt = {
        labels: noLables,
        rowCount: -1
    };
    var noTotalOpt = {
        labels: noLables
    };
    var gridNameSpace = '.rs.jquery.bootgrid';

    function BGrid(opt) {
        var self = this;
        var _opt = $.extend({}, defaultGridOpt, opt);

        /**
         * 自定义requestHandler
         */
        _opt.requestHandler = getRequestHanlder(_opt.requestHandler, _opt);


        _opt.responseHandler = getResponseHandler(_opt.responseHandler);
        if (_opt.isPager === true) {
            _opt = $.extend({}, _opt, noPagerOpt);
        }
        else if (_opt.noTotal === true) {
            _opt = $.extend({}, _opt, noTotalOpt);
        }
        this.option = _opt;
        $.each(self.option.events, function (i, item) {
            $(self.option.id).on(item.name + gridNameSpace, item.event);
        });
        //先绑定事件
        this.bGrid = $(this.option.id).bootgrid(this.option);
    }

    var bgProto = BGrid.prototype;
    //刷新Grid
    bgProto.reload = function () {
        this.bGrid.bootgrid('search', new Date().getTime());
    };

    bgProto.call=function () {
        this.bGrid.bootgrid();
    };

    //公共返回选中行数，没有则返回空数组
    bgProto.getSelections = function () {
        var self = this;
        var selectedRows = [];
        $('tbody :checkbox:checked', this.bGrid).each(function (i, item) {
            selectedRows.push($(this).val());
        });
        return selectedRows;
    };
    bgProto.getCount = function () {
        return $(this.option.id).bootgrid('getTotalRowCount');
    };
    bgProto.on = function (eventName, callback) {
        var self = this;
        $(self.option.id).on(eventName + gridNameSpace, callback);
    };
    //grid
    //exporter.BGrid = BGrid;
    if (!window.BT) {
        window.BT = {};
    }

    window.BT.BGrid = BGrid;
})();